package daily_exercise;

/**
 * @Author self
 * @Date 2025/8/6 9:53
 * @Describe Guava作本地缓存示例
 */
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class GuavaCacheExample {

    public static void main(String[] args) throws ExecutionException {
        // 创建一个LoadingCache实例，配置为最大容量为100，过期时间为10分钟
        LoadingCache<String, String> cache = CacheBuilder.newBuilder()
                .maximumSize(100) // 设置缓存的最大容量
                .expireAfterWrite(10, TimeUnit.MINUTES) // 设置写入后10分钟过期
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        // 如果没有找到对应的key，则返回默认值或抛出异常
                        return "Default Value for " + key;
                    }
                });

        // 放入缓存项
        cache.put("key1", "value1");

        // 获取缓存项
        System.out.println("Value for key1: " + cache.get("key1"));

        // 尝试获取不存在的键，将会调用load方法加载默认值
        System.out.println("Value for key2: " + cache.get("key2"));

        // 删除缓存项
        cache.invalidate("key1");
        System.out.println("After invalidate key1, value for key1: " + cache.get("key1"));
    }
}